package io.task.message.socket;

import io.task.message.socket.thread.ThreadUtils;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Setter
@Getter
public class IoUtils {

    public static boolean checkBeforeIO(ChannelContext channelContext) {
        if (channelContext.isWaitingClose) {
            return false;
        }

        Boolean isopen = null;
        if (channelContext.asynchronousSocketChannel != null) {
            isopen = channelContext.asynchronousSocketChannel.isOpen();

            if (channelContext.isClosed || channelContext.isRemoved) {
                if (isopen) {
                    try {
                        Io.close(channelContext,
                                "asynchronousSocketChannel is open, but channelContext isClosed: " + channelContext.isClosed + ", isRemoved: " + channelContext.isRemoved, ChannelContext.CloseCode.CHANNEL_NOT_OPEN);
                    } catch (Throwable e) {
                        log.error(e.toString(), e);
                    }
                }
                log.info("{}, isopen:{}, isClosed:{}, isRemoved:{}", channelContext, isopen, channelContext.isClosed, channelContext.isRemoved);
                return false;
            }
        } else {
            log.error("{}, 请检查此异常, asynchronousSocketChannel is null, isClosed:{}, isRemoved:{}, {} ", channelContext, channelContext.isClosed, channelContext.isRemoved,
                    ThreadUtils.stackTrace());
            return false;
        }

        if (!isopen) {
            log.info("{}, 可能对方关闭了连接, isopen:{}, isClosed:{}, isRemoved:{}", channelContext, isopen, channelContext.isClosed, channelContext.isRemoved);
            Io.close(channelContext, "asynchronousSocketChannel is not open, 可能对方关闭了连接", ChannelContext.CloseCode.CHANNEL_NOT_OPEN);
            return false;
        }
        return true;
    }

}
